<template>
  <div class="list-container">
    <van-pull-refresh 
    v-model="refreshing" 
    :success-text="refreshCount"
    :success-duration="1500" 
    @refresh="onRefresh">
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        :error.sync="error"
        error-text="请求失败，点击重新加载"
        offset="0"
        @load="onLoad"
      >
        <article-item v-for="(article,index) in list" :key="index" :article="article"/>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import {getArticleListAPI} from '@/api'
import ArticleItem from '@/components/ArticleItem'
export default {
  name:'ArticleList',
  data(){
    return {
      list: [],//存储数据
      loading: false,//控制加载状态
      finished: false,//控制加载结束状态
      timestamp:null,//请求获取下一页的时间戳
      error:false,
      refreshing:false,//下拉刷新loading状态
      refreshCount:'刷新成功',
      timer:null
    }
  },
  props:{
    channels:{
      type:Object ,
      required:true
    }
  },
  components:{
    ArticleItem
  },
  methods:{
   async onLoad(){
        this.time=setTimeout(async ()=>{
        try{
        const {data}=await getArticleListAPI({
          channel_id:this.channels.id,
          timestamp:this.timestamp||Date.now(),
          with_top:1
        })
        // 模拟出错
        // if(Math.random()>0.5){
        //   JSON.parse('jiogueiro')
        // }
        const{results}=data.data
        // this.list=[...this.list,results]
        this.list.push(...results)
        this.loading=false
        if(results.length){
          this.timestamp=data.data.pre_timestamp
        }else{
          this.finished=true
        }
        }catch(err){
          this.loading=false
          this.error= true
        }
      },800)
   },
    async onRefresh() {
      try{
          const {data}=await getArticleListAPI({
          channel_id:this.channels.id,
          timestamp:Date.now(),
          with_top:1
        })
        //  模拟出错
        // if(Math.random()>0.4){
        //   JSON.parse('jiogueiro')
        // }
          const{results}=data.data
          this.list.unshift(...results)
          this.refreshing=false;
          this.refreshCount=`刷新成功,更新了${results.length}条数据`
      }catch(err){
          this.refreshing=false;
          this.refreshCount=`刷新失败`

      }
    
      
    },
  },
  beforeDestroy(){
    this.timer=null
  }
}


</script>

<style scoped lang="less">



</style>